package web4;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.ImageIO;

public class CheckServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("image/jpeg");

        // 创建内存图像
        BufferedImage bufferedImage = new BufferedImage(160, 40, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bufferedImage.createGraphics();

        // 设置背景色
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, 160, 40);

        // 设置字体
        Font font = new Font("Fixedsys", Font.BOLD, 20);
        g2d.setFont(font);

        Random random = new Random();

        // 添加干扰线
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt(160);
            int y = random.nextInt(40);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g2d.setColor(getRandomColor());
            g2d.drawLine(x, y, x + xl, y + yl);
        }

        // 添加随机字符
        String code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        float yawpRate = 0.05f; // 噪声率
        int codeCount = 6; // 验证码字符数
        for (int i = 0; i < codeCount; i++) {
            String strRand = String.valueOf(code.charAt(random.nextInt(code.length())));
            g2d.setColor(getRandomColor());
            g2d.drawString(strRand, 30 * i + 6, 24);
        }

        // 将验证码存入session
        String capText = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        StringBuilder captchaCode = new StringBuilder();
        for (int i = 0; i < codeCount; i++) {
            int index = random.nextInt(capText.length());
            captchaCode.append(capText.charAt(index));
        }
        request.getSession().setAttribute("captcha", captchaCode.toString());

        g2d.dispose();

        // 输出图像
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bufferedImage, "jpeg", out);
        IoUtils.closeQuietly(out);
    }

    private Color getRandomColor() {
        Random random = new Random();
        return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
    }
}